package com.ddtech.business.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddtech.business.constant.BusinessEnum;
import com.ddtech.business.web.entity.Banner;
import com.ddtech.business.web.mapper.BannerMapper;
import com.ddtech.business.web.query.BannerQuery;
import com.ddtech.business.web.service.BannerService;
import com.ddtech.exception.BizPreconditions;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 轮播图 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-03-09
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {

    @Override
    public Object pageList(BannerQuery bannerQuery) {
        IPage<Banner> page = this.page(bannerQuery.populatePage(), bannerQuery.autoWrapper());
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Object pageListPc(BannerQuery bannerQuery) {
        IPage<Banner> page = this.page(bannerQuery.populatePage(), bannerQuery.autoWrapper());
        List<Banner> list= page.getRecords().stream().map((banner) -> {
            String url=banner.getImageUrl();
            if(StringUtils.isNotEmpty(url)){
                JSONArray array = JSON.parseArray(url);
                if (array!=null && array.size()>0){
                    JSONObject json=array.getJSONObject(0);
                    banner.setImageUrl(json.getString("url"));
                }
            }
            return banner;
        }).collect(Collectors.toList());
        return PageUtil.toPage(list, page.getTotal());
    }

    @Override
    public void create(Banner banner) {
        banner.init();
        this.saveOrUpdate(banner);
    }

    @Override
    public void del(String id) {
        Banner banner = this.getById(id);
        BizPreconditions.check(banner == null, BusinessEnum.QUERY_ERROR.getMsg());
        banner.baseDelete();
        this.saveOrUpdate(banner);
    }
}
